package com.ebt.m;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.os.StrictMode;
import android.os.SystemClock;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.ebt.m.activity.LoginActivity;
import com.ebt.m.cloud.downloader.DownloadService;
import com.ebt.m.cloud.downloader.config.Config;
import com.ebt.m.commons.BaseApplication;
import com.ebt.m.data.DatabaseManager;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.greendao.DaoMaster;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.android.EBTUserInfoHelper;
import com.squareup.leakcanary.LeakCanary;
import com.tendcloud.tenddata.TCAgent;


public class AppContext extends BaseApplication {

    private static DaoMaster daoMaster;
    private static UserInfo mCurrentUser;// 当前用户，全局静态变量

    private static AppContext mInstance;
    public static long deltaTime;

    public static AppContext getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
        mInstance = this;
//        JPushUtil.init(this);
        com.ebt.m.data.middle.AppContext.setmContext(mInstance);
        initUser();
        TCAgent.init(getApplicationContext());
        TCAgent.setReportUncaughtExceptions(true);

        Config config = new Config();
        DownloadService.getDownloadManager(this.getApplicationContext(), config);

        //解决android N（>=24）系统以上分享 路径为file://时的 android.os.FileUriExposedException异常
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
    }


    @Override
    public boolean isDebug() {
        return BuildConfig.ISDEBUG;
    }

    @Override
    public String getAuthorization() {
        return getCurrentUser().getAccessToken();
    }

    @Override
    public long currentTime() {
        return getCurrentTime();
    }


    private void initUser() {
        UserInfo userInfo = EBTUserInfoHelper.getUserFromPreferences();
        mCurrentUser = userInfo;
    }

    /**
     * 取得DaoMaster
     *
     * @return
     */
    public DaoMaster getDaoMaster() {
        if (daoMaster == null) {
            int version = DatabaseManager.getInstance(getBaseContext()).getDbVersion();
            SQLiteOpenHelper helper = new SQLiteOpenHelper(getBaseContext(), ConfigData.DATABASE, null, version) {

                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                }

                @Override
                public void onCreate(SQLiteDatabase db) {
                }

                @Override
                public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                }
            };
            daoMaster = new DaoMaster(helper.getWritableDatabase());

        }
        return daoMaster;
    }

    public static UserInfo getCurrentUser() {
        if (mCurrentUser == null) {
            mCurrentUser = new UserInfo();
        }
        return mCurrentUser;
    }

    public static void setCurrentUser(UserInfo user) {
        mCurrentUser.set(user);
    }

    public void exitApp() {
        System.exit(0);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static void loginOut(Context context) {
        clearLoginInfo(context);
        Intent intent = new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);

    }

    public static void clearLoginInfo(Context context) {
//        JPushUtil.resetAlisAndTagsWhenLogout(context);
        AppContext.getCurrentUser().clearUserInfo();
        EBTUserInfoHelper.deleteUserInfo();
    }

    public static long getCurrentTime() {
        if (deltaTime == 0) {
            return System.currentTimeMillis();
        }
        return SystemClock.elapsedRealtime() + deltaTime;
    }

}
